package networking.messages;

import java.util.ArrayList;
import java.util.Iterator;

import logic.common.Squad;
import logic.common.game.Game;
import logic.common.player.Player;
import logic.common.team.Team;
import logic.common.team.processes.TeamProcess;
import map.spawnStation.SpawnStation;
import networking.messages.playerMessages.PlayerAddMessage;
import networking.messages.syncMessages.SpawnStationSyncMessage;
import networking.messages.teamMessages.ProcessCreateMessage;

public class GameStartMessage extends SimpleMessage {
	
	private ArrayList<PlayerAddMessage> playerAddMessages;
	private ArrayList<SpawnStationSyncMessage> spawnSyncMessages;
	private ArrayList<SquadUpdateMessage> squadUpdateMessages;
	private ArrayList<ProcessCreateMessage> processCreateMessages;
	
	public GameStartMessage() {
		super();
	}
	
	public GameStartMessage(Game game) {
		this();
		
		Team teamA = game.getTeamA();
		Team teamB = game.getTeamB();
		
		playerAddMessages = new ArrayList<PlayerAddMessage>();
		addPAMs(teamA);
		addPAMs(teamB);
		
		spawnSyncMessages = new ArrayList<SpawnStationSyncMessage>();
		
		for(SpawnStation station : game.getMap().getSpawnStations()) {
			if(station.getCapturePoints() == 0f) continue;
			
			SpawnStationSyncMessage sssm = new SpawnStationSyncMessage(station, station.getLastCapturingPlayer());
			spawnSyncMessages.add(sssm);
		}
		
		squadUpdateMessages = new ArrayList<SquadUpdateMessage>();
		addSUM(teamA);
		addSUM(teamB);
		
		processCreateMessages = new ArrayList<ProcessCreateMessage>();
		addPCMs(teamA);
		addPCMs(teamB);
	}
	
	private void addSUM(Team team) {
		Iterator<Squad> iter = team.getAllSquadIterator();
		while(iter.hasNext()) {
			Squad squad = iter.next();
			if(!squad.isEmpty()) {
				SquadUpdateMessage sum = new SquadUpdateMessage(squad);
				squadUpdateMessages.add(sum);
			}
		}
	}
	
	private void addPAMs(Team team) {
		for(Player player : team.getAllPlayers()) {
			PlayerAddMessage pam = new PlayerAddMessage(player);
			playerAddMessages.add(pam);
		}
	}
	
	private void addPCMs(Team team) {
		TeamProcess activeProcess = team.getActiveTeamProcess();
		if(activeProcess != null) processCreateMessages.add(activeProcess.getProcessCreateMessage());
		
		for(TeamProcess process : team.getPendingTeamProcesses()) {
			ProcessCreateMessage pcm = process.getProcessCreateMessage();
			processCreateMessages.add(pcm);
		}
	}
	
	public ArrayList<PlayerAddMessage> getPAMs() { return playerAddMessages; }
	
	public ArrayList<SpawnStationSyncMessage> getSpawnSyncMessages() { return spawnSyncMessages; }
	
	public ArrayList<SquadUpdateMessage> getSUMs() { return squadUpdateMessages; }
	
	public ArrayList<ProcessCreateMessage> getPCMs() { return processCreateMessages; }
}